package com.github.niefy.modules.wxma.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.niefy.config.TaskExcutor;
import com.github.niefy.modules.wx.entity.TemplateMsgLog;
import com.github.niefy.modules.wx.entity.WxUser;
import com.github.niefy.modules.wx.form.TemplateMsgBatchForm;
import com.github.niefy.modules.wx.service.MsgTemplateService;
import com.github.niefy.modules.wx.service.TemplateMsgLogService;
import com.github.niefy.modules.wx.service.TemplateMsgService;
import com.github.niefy.modules.wx.service.WxUserService;
import com.github.niefy.modules.wxma.service.MaTemplateMsgService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Nifury
 * @date 2017-9-27
 */
@Service
@RequiredArgsConstructor
public class MaTemplateMsgServiceImpl implements MaTemplateMsgService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TemplateMsgLogService templateMsgLogService;

    private final WxMaService wxMaService;
    @Autowired
    MsgTemplateService msgTemplateService;
    @Autowired
    WxUserService wxUserService;


    /**
     * 发送微信模版消息,使用固定线程的线程池
     */
    @Override
    @Async
    public void sendTemplateMsg(WxMaSubscribeMessage msg, String appid) {
        TaskExcutor.submit(() -> {
            String result;
            try {
                msg.setMiniprogramState("formal");
                msg.setLang("zh_CN");
                wxMaService.switchover(appid);
                wxMaService.getMsgService().sendSubscribeMsg(msg);
                result = "{\"errcode\":0,\"errmsg\":\"ok\"}";
            } catch (WxErrorException e) {
                result = e.getMessage();
            }

            //保存发送日志
            TemplateMsgLog log = new TemplateMsgLog(msg,appid, result);
            templateMsgLogService.addLog(log);
        });
    }

    @Override
    @Async
    public void sendMsgBatch(TemplateMsgBatchForm form, String appid) {
        logger.info("批量发送模板消息任务开始,参数：{}", form.toString());
        wxMaService.switchover(appid);

        //模板推送
        List<WxMaSubscribeMessage.MsgData> msgDatas = new ArrayList<>();
        form.getData().forEach(wxMpTemplateData -> {
            msgDatas.add(new WxMaSubscribeMessage.MsgData(wxMpTemplateData.getName(), wxMpTemplateData.getValue()));
        });
        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .toUser(form.getOpenid())
                .templateId(form.getTemplateId())
                .data(msgDatas)
                .page(form.getMiniprogram().getPagePath())
                .build();

        this.sendTemplateMsg(message, appid);
        logger.info("批量发送模板消息任务结束");
    }


    @Override
    @Async
    public void sendMaMsg(TemplateMsgBatchForm form) {
        logger.info("发送模板消息任务开始,参数：{}", form.toString());
        wxMaService.switchover(form.getAppid());

        //模板推送
        List<WxMaSubscribeMessage.MsgData> msgDatas = new ArrayList<>();
        form.getData().forEach(wxMpTemplateData -> {
            msgDatas.add(new WxMaSubscribeMessage.MsgData(wxMpTemplateData.getName(), wxMpTemplateData.getValue()));
        });
        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .toUser(form.getOpenid())
                .templateId(form.getTemplateId())
                .data(msgDatas)
                .page(form.getMiniprogram().getPagePath())
                .build();

        this.sendTemplateMsg(message, form.getAppid());
        logger.info("发送模板消息任务结束");
    }

}
